from django.core.cache import cache
from functools import wraps
from rest_framework.response import Response


# 缓存装饰器
def wrap_cache(func):
    # 伪装装饰器
    @wraps(func)
    def inner(self, request, *args, **kwargs):
        # 获取cache_key
        cache_key = getattr(self, 'cache_key', None)
        assert cache_key, KeyError('cache_key not none')
        # 从redis中获取缓存
        result_cache = cache.get(cache_key)
        if result_cache:
            return Response(result_cache)
        # 如果缓存中没有  # 设置缓存
        res = func(self, request, *args, **kwargs)
        # print(res.__dict__)
        # res是Response对象，所以数据从data中获取
        cache.set(cache_key, res.data)
        return res

    return inner
